package openmarket.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import openmarket.dao.UserDAO;
import openmarket.dao.dataobject.UserDO;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class UserManagerController implements Controller {
	private UserDAO userDAO;

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String action = request.getParameter("action");
		ModelAndView modAndView = new ModelAndView();
		if (action == null) {
			String reqpath = request.getRequestURI();
			String targetUrl1 = reqpath.replaceFirst("/", "");
			String targetUrl2 = reqpath.replaceAll(".html|.htm", "");
			modAndView.setViewName(targetUrl2);
		} else if (action.equals("add")) {
			userDAO.addUser(setFrom2User(request));
			modAndView.addObject("user", userDAO.getUserByName(request.getParameter("name")));
			modAndView.setViewName("viewUser");
		}
		return modAndView;
	}
	
	public UserDO setFrom2User(HttpServletRequest request){
		UserDO u = new UserDO();
		u.setAddress(request.getParameter("address"));
		u.setName(request.getParameter("name"));
		u.setAge(Integer.parseInt(request.getParameter("age")));
		u.setPassword(request.getParameter("password"));
		u.setPhone(Long.parseLong(request.getParameter("phone")));
		u.setWebSite(request.getParameter("webSite"));
		return u;
	}

}
